package server.main;

import java.net.*;				
import java.io.*;		
import java.util.Scanner;
import java.util.StringTokenizer;
				
public class TestClient{				
				
	public static void main(String[] args) {			
		try{		
			Socket sock = new Socket("127.0.0.1", 10001);	
			BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));	
			Scanner scanner = new Scanner(System.in);
			
			OutputStream out = sock.getOutputStream();	
			InputStream in = sock.getInputStream();	
			PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "ms949"));	
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "ms949"));	
			String line = null;	
			//while((line = keyboard.readLine()) != null){
			while((line = scanner.next()) != null){				
				
				if(line.equals("quit")) break;
				
				System.out.println("input : " + line);
				pw.println(line);
				pw.flush();
				String echo = br.readLine();
				
				if(checkSuccess(echo)){
					parsePrint(echo);
				}
				
			
										
				StringTokenizer st1 = new StringTokenizer(echo, "^");
				while (st1.hasMoreTokens()) 
				{
					System.out.println(st1.nextToken());
					/*					
					StringTokenizer st2 = new StringTokenizer(st1.nextToken(), "|");
					while (st2.hasMoreTokens()) 
					{							
						System.out.println(st2.nextToken());
					}
					*/
				}
			
			}	
			pw.close();	
			br.close();	
			sock.close();	
		}catch(Exception e){		
			System.out.println(e);	
		}		
	}
	
	
	public static String[] parseResultString(String param, String delim){		
		return param.split(delim);
	}
	
	public static void parsePrint(String param){
		
		System.out.println("parsePrint start");
		String [] parsedRow = parseResultString(param, "\\^");				
		for(int outer = 0 ; outer < parsedRow.length ; outer++){
			String[] parsedField = parseResultString(parsedRow[outer], "|");
			for(int inner = 0 ; inner < parsedField.length ; inner++){
				System.out.print(parsedField[inner] + " ");
			}
			System.out.println();
		}
		System.out.println("parsePrint end");
	}
	
	public static boolean checkSuccess(String param){
		if("FAIL".equals(param.substring(0, 4))){
			System.out.println("REQUEST FAIL : " + param);
			return false;
		} else {			
			return true;
		}
	}
}				
